<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 公共样式 -->
    <link rel="stylesheet" href="../css/common.css">
    <!-- 1. 引入 Axios（接口请求库） -->
    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.8/dist/axios.min.js"></script>
    <!-- 2. 引入 Moment.js（时间格式化库） -->
    <script src="https://cdn.jsdelivr.net/npm/moment@2.30.1/moment.min.js"></script>
    <!-- 3. 引入 Common 工具类（原有） -->
    <script src="../js/common.js"></script>
</head>
<body>
<div class="container">
    <!-- 页面标题和新增按钮 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>用户管理</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userModal">
            新增用户
        </button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
        <div class="row g-3">
            <div class="col-md-4">
                <input type="text" id="searchPhone" class="form-control" placeholder="输入手机号搜索">
            </div>
            <div class="col-md-3">
                <select id="searchCity" class="form-select">
                    <option value="">请选择城市</option>
                </select>
            </div>
            <div class="col-md-2">
                <button class="btn btn-success w-100" onclick="queryUserList(1)">搜索</button>
            </div>
            <div class="col-md-2">
                <button class="btn btn-light w-100" onclick="resetSearch()">重置</button>
            </div>
        </div>
    </div>

    <!-- 用户列表表格 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-hover table-bordered">
                <thead class="table-primary">
                <tr>
                    <th>用户ID</th>
                    <th>用户名</th>
                    <th>手机号</th>
                    <th>性别</th>
                    <th>城市</th>
                    <th>注册时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="userTableBody">
                <!-- 数据将通过JS动态渲染 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 分页组件 -->
    <div id="pagination-container"></div>
</div>

<!-- 新增/编辑用户弹窗 -->
<div class="modal fade" id="userModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">新增用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    <input type="hidden" id="userId"> <!-- 编辑时存储用户ID -->
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="username" class="form-label">用户名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="username" required placeholder="请输入用户名">
                        </div>
                        <div class="col-md-6">
                            <label for="phone" class="form-label">手机号 <span class="text-danger">*</span></label>
                            <input type="tel" class="form-control" id="phone" required placeholder="请输入手机号">
                        </div>
                        <div class="col-md-6">
                            <label for="sex" class="form-label">性别 <span class="text-danger">*</span></label>
                            <select class="form-select" id="sex" required>
                                <option value="">请选择性别</option>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="cityId" class="form-label">城市 <span class="text-danger">*</span></label>
                            <select class="form-select" id="cityId" required>
                                <option value="">请选择城市</option>
                            </select>
                        </div>
                        <div class="col-md-12">
                            <label for="idNumber" class="form-label">身份证号</label>
                            <input type="text" class="form-control" id="idNumber" placeholder="请输入身份证号（选填）">
                        </div>
                        <div class="col-md-12">
                            <label for="avatar" class="form-label">头像URL</label>
                            <input type="url" class="form-control" id="avatar" placeholder="请输入头像URL（选填）">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- 公共JS -->
<script src="../js/common.js"></script>
<script>
    // 分页参数
    let currentPage = 1;
    const pageSize = 10;

    // 页面加载时初始化
    window.onload = function () {
        // 加载城市列表（搜索框和表单）
        SelectData.loadCities("searchCity");
        SelectData.loadCities("cityId");
        // 查询用户列表
        queryUserList(currentPage);
    };

    // 查询用户列表
    async function queryUserList(pageNum) {
        try {
            const phone = document.getElementById("searchPhone").value;
            const cityId = document.getElementById("searchCity").value;
            // 调用后端分页接口
            const res = await axios.get(`/api/users/page`, {
                params: {
                    pageNum: pageNum,
                    pageSize: pageSize,
                    phone: phone,
                    cityId: cityId
                }
            });
            const { records, total } = res.data;
            currentPage = pageNum;

            // 渲染表格
            const tableBody = document.getElementById("userTableBody");
            tableBody.innerHTML = "";
            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="7" class="text-center">暂无数据</td></tr>';
                return;
            }

            records.forEach(user => {
                const row = `
                        <tr>
                            <td>${user.userId}</td>
                            <td>${user.username}</td>
                            <td>${user.phone}</td>
                            <td>${user.sex}</td>
                            <td>${user.city?.province} - ${user.city?.cityName || '未选择'}</td>
                            <td>${Common.formatDate(user.registerTime)}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="editUser(${user.userId})">编辑</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteUser(${user.userId})">删除</button>
                            </td>
                        </tr>
                    `;
                tableBody.innerHTML += row;
            });

            // 渲染分页
            Common.renderPagination(total, pageNum, pageSize, queryUserList);
        } catch (err) {
            Common.errorMsg("查询用户失败：" + err.message);
        }
    }

    // 重置搜索条件
    function resetSearch() {
        document.getElementById("searchPhone").value = "";
        document.getElementById("searchCity").value = "";
        queryUserList(1);
    }

    // 编辑用户
    async function editUser(userId) {
        try {
            const res = await axios.get(`/api/users/${userId}`);
            const user = res.data;
            // 填充表单
            document.getElementById("userId").value = user.userId;
            document.getElementById("username").value = user.username;
            document.getElementById("phone").value = user.phone;
            document.getElementById("sex").value = user.sex;
            document.getElementById("cityId").value = user.cityId;
            document.getElementById("idNumber").value = user.idNumber || "";
            document.getElementById("avatar").value = user.avatar || "";
            // 更改弹窗标题
            document.getElementById("modalTitle").textContent = "编辑用户";
            // 显示弹窗
            new bootstrap.Modal(document.getElementById("userModal")).show();
        } catch (err) {
            Common.errorMsg("加载用户信息失败：" + err.message);
        }
    }

    // 保存用户（新增/编辑）
    async function saveUser() {
        // 表单校验
        const username = document.getElementById("username").value;
        const phone = document.getElementById("phone").value;
        const sex = document.getElementById("sex").value;
        const cityId = document.getElementById("cityId").value;
        if (!username || !phone || !sex || !cityId) {
            Common.errorMsg("请填写必填字段！");
            return;
        }

        // 构建用户数据
        const userData = {
            username: username,
            phone: phone,
            sex: sex,
            cityId: cityId,
            idNumber: document.getElementById("idNumber").value,
            avatar: document.getElementById("avatar").value
        };
        const userId = document.getElementById("userId").value;

        try {
            if (userId) {
                // 编辑：PUT请求
                userData.userId = userId;
                await axios.put("/api/users", userData);
                Common.successMsg("编辑用户成功！");
            } else {
                // 新增：POST请求
                await axios.post("/api/users", userData);
                Common.successMsg("新增用户成功！");
            }
            // 关闭弹窗并刷新列表
            bootstrap.Modal.getInstance(document.getElementById("userModal")).hide();
            queryUserList(currentPage);
            // 重置表单
            document.getElementById("userForm").reset();
            document.getElementById("userId").value = "";
            document.getElementById("modalTitle").textContent = "新增用户";
        } catch (err) {
            Common.errorMsg("保存用户失败：" + err.message);
        }
    }

    // 删除用户
    function deleteUser(userId) {
        Common.confirmMsg("确定要删除该用户吗？", async () => {
            try {
                await axios.delete(`/api/users/${userId}`);
                Common.successMsg("删除用户成功！");
                queryUserList(currentPage);
            } catch (err) {
                Common.errorMsg("删除用户失败：" + err.message);
            }
        });
    }
</script>
</body>
</html>